using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Text;
using System.Windows.Forms;
using ctsu.Admin.Forms.CoreLab;

using Syncfusion.Windows.Forms.Grid;
using Syncfusion.Windows.Forms.Tools;
using ctsu.Admin.Forms;
using ctsu.BaseForms;
using ctsu.Security;
using ctsu.Data;
using ctsu.Shared;

namespace ctsu.Admin.BusLogic.CoreLab
{

	public class BLFormNewFromExisting : BLCoreLabFormBaseImpl
	{
		private ArrayList _alExistIDs;

		#region control references
		private TextBox _id;
		private DateTimePickerAdv _batchOutDate;

		private ComboBox _testType;
		private ComboBox _testOutTo;
		private ComboBox _unitOfMeasure;

		private DateTimePickerAdv _outDate;
		private TextBox _result;
		private TextBox _note;

		private Button _btnRetrieveItems;
		private Button _btnClear;
		private Button _btnEditBatch;
		private Button _btnRemoveBatch;
		private Button _btnPrint;
		private Button _btnGrid;
		private CheckBox _chkGridTracking;
		#endregion control references

		#region initialize
		//initialize control references
		public BLFormNewFromExisting(FormMain formMain, FormBase form, FormInfoBase formInfo, DataTable tableSchema, Permission formSecurity, Hashtable configData)
			: base(formMain, form, formInfo, tableSchema, formSecurity, configData)
		{
		}

		protected override void _vcManager_OnAfterHookEvents()
		{
			_id = (TextBox)Forms.Utils.GetControlByName("ID", this._form.Controls);
			_batchOutDate = (DateTimePickerAdv)Forms.Utils.GetControlByName("BatchOutDate", this._form.Controls);

			_testOutTo = (ComboBox)Forms.Utils.GetControlByName("TestOutTo", this._form.Controls);
			_testType = (ComboBox)Forms.Utils.GetControlByName("TestType", this._form.Controls);
			_unitOfMeasure = (ComboBox)Forms.Utils.GetControlByName("UnitOfMeasure", this._form.Controls);

			_result = (TextBox)Forms.Utils.GetControlByName("Result", this._form.Controls);
			_note = (TextBox)Forms.Utils.GetControlByName("Note", this._form.Controls);
			_outDate = (DateTimePickerAdv)Forms.Utils.GetControlByName("OutDate", this._form.Controls);

			_btnRetrieveItems = (Button)Forms.Utils.GetControlByName("btnRetrieveItems", this._form.Controls);
			_btnClear = (Button)Forms.Utils.GetControlByName("btnClear", this._form.Controls);
			_btnRemoveBatch = (Button)Forms.Utils.GetControlByName("btnRemoveBatch", this._form.Controls);
			_btnEditBatch = (Button)Forms.Utils.GetControlByName("btnEditBatch", this._form.Controls);
			_btnGrid = (Button)Forms.Utils.GetControlByName("btnGrid", this._form.Controls);
			_btnPrint = (Button)Forms.Utils.GetControlByName("btnPrint", this._form.Controls);
			_chkPrintReport = (CheckBox)Forms.Utils.GetControlByName("chkPrintReport", this._form.Controls);
			_chkPerPatient = (CheckBox)Forms.Utils.GetControlByName("chkPerPatient", this._form.Controls);
			_chkPrintSelected = (CheckBox)Forms.Utils.GetControlByName("chkPrintSelected", this._form.Controls);
			_chkGridTracking = (CheckBox)Forms.Utils.GetControlByName("chkGridTracking", this._form.Controls);

			this._form.btnRemove.Visible = false;
			this._form.btnEdit.Visible = false;
			this._form.btnSearch.Visible = false;
			_chkGridTracking.Visible = false;
			_btnGrid.Visible = false;

		}

		public override void InitializeEmptyControls()
		{
			base.InitializeEmptyControls();
			this._testOutTo.SelectedIndex = -1;
			this._testOutTo.SelectedIndex = -1;
			this._testType.SelectedIndex = -1;
			this._testType.SelectedIndex = -1;
			this._unitOfMeasure.SelectedIndex = -1;
			this._unitOfMeasure.SelectedIndex = -1;
			this._outDate.Value = DateTime.Today;
			this._outDate.IsNullDate = true;
		}

		protected override void SetControlsEnabled(bool enable)
		{
			base.SetControlsEnabled(enable);
			_btnClear.Enabled = enable;
			_btnRetrieveItems.Enabled = enable;

			if (enable == false)
			{
				_btnEditBatch.Enabled = enable;
				_btnRemoveBatch.Enabled = enable;
			}


			_testOutTo.SelectedIndex = -1;
			_testOutTo.SelectedIndex = -1;
			_testOutTo.Enabled = enable;

			_testType.SelectedIndex = -1;
			_testType.SelectedIndex = -1;
			_testType.Enabled = enable;

			_unitOfMeasure.SelectedIndex = -1;
			_unitOfMeasure.SelectedIndex = -1;
			_unitOfMeasure.Enabled = enable;

			_outDate.Value = this._batchOutDate.Value;
			_outDate.IsNullDate = true;
			_outDate.Enabled = enable;

			_result.Text = "";
			_result.Enabled = enable;

			_note.Text = "";
			_note.Enabled = enable;

		}
		#endregion initialize

		private void RemoveFromList(int origID)
		{
			foreach (int i in _alExistIDs)
			{
				if (i == origID)
				{
					_alExistIDs.Remove(i);
					break;
				}
			}
		}

		public override void GenericClick(Control sender)
		{
			if (sender.Name == "btnRetrieveItems")
				SelectSamples();
			if (sender.Name == "btnEditBatch")
				EditBatch();
			if (sender.Name == "btnRemoveBatch")
				RemoveBatch();
			if (sender.Name == "btnClear")
				ClearInfo();
			if (sender.Name == "btnPrint")
				DoPrint();
			if (sender.Name == "btnNewTest")
				NewTest();
			if (sender.Name == "btnNewUnit")
				NewUnit();
		}

		public override void New()
		{
			this._alExistIDs = new ArrayList();
			base.New();
		}

		public override bool Save()
		{
			bool b = base.Save();
			//display the existing id data
			BLCoreLabFormGridBaseImpl fgbl = (BLCoreLabFormGridBaseImpl)_gridBLs["TestSamples"];
			GridControl grid = fgbl.Grid;
			for (int i = 1; i < grid.RowCount + 1; i++)
			{
				grid[i, 2].CellValue = (int)this._alExistIDs[i - 1];
			}

			return b;

		}

		#region select samples
		private void SelectSamples()
		{
			SampleChooserDlg dlc = new SampleChooserDlg();
			dlc.Owner = this._form;
			dlc.Text = "Select Samples";
			dlc.SelectSampleClick += new ctsu.Admin.Forms.CoreLab.SampleChooserDlg.SelectSampleButtonClickEventHandler(dlc_SelectSampleClick);
			dlc.Show();
		}

		private void dlc_SelectSampleClick(object sender, SelectSamplesEventArgs e)
		{
			if (e.SelectType == 0)
				RetrieveSampleBatch(e.ID);
			else
				RetrieveOneSample(e.ID, true);

			BLCoreLabFormGridBaseImpl fgbl = (BLCoreLabFormGridBaseImpl)_gridBLs["TestSamples"];
			GridControl grid = fgbl.Grid;
			if (grid.RowCount > 0)
			{
				if (!this._btnEditBatch.Enabled)
				{
					this._btnEditBatch.Enabled = true;
					this._btnRemoveBatch.Enabled = true;
					this._form.btnSave.Enabled = true;
				}
			}
		}

		private void RetrieveOneSample(int id, bool displayMessage)
		{
			StringBuilder sb = new StringBuilder();

			if (IsInList(id))
			{
				if (displayMessage)
				{
					sb.Append("Sample ID: " + id + " is already in the list");
					MessageBox.Show(this._form, sb.ToString(), "Duplicate ID",
						MessageBoxButtons.OK, MessageBoxIcon.Information);
				}
				return;
			}

			string sql = "SELECT t.ID, t.DrawSample, t.BatchInNum, " +
				" d.Protocol, d.Patient " +
				" FROM TestSamples t,DrawSamples d" +
				" WHERE t.ID =" + id +
				" AND d.ID=t.DrawSample";

			BLCoreLabFormGridBaseImpl fgbl = (BLCoreLabFormGridBaseImpl)_gridBLs["TestSamples"];
			GridControl grid = fgbl.Grid;

			//SqlConnection conn = LoginForm.GetSqlConnection();			
			IDataReader reader = null;
			try
			{
				reader = DataAccess.GetDataReader(sql);

				Sample samp = null;
				string message = "";

				grid.BeginUpdate();
				if (reader.Read())
				{
					Cursor.Current = Cursors.WaitCursor;
					samp = new Sample();
					samp.Tag = reader.GetInt32(0);
					samp.DrawID = reader.GetInt32(1);
					samp.BatchInNum = reader.GetInt32(2);
					samp.Protocol = reader.GetInt32(3);
					//get protocolInfo
					samp.ProtocolInfo = CoreLabUtils.GetProtocolInfo(samp.Protocol, out message);

					samp.PatientID = reader.GetInt32(4);
					//get the patient info
					samp.PatientInfo = CoreLabUtils.GetPatientInfo(samp.PatientID, out message);
					fgbl.AddRow(samp, 0);
					_alExistIDs.Add(samp.Tag);
				}
				else
				{
					sb.Append("Sample ID: " + id + " could not be found");
					MessageBox.Show(this._form, sb.ToString(), "Sample Not Found",
						MessageBoxButtons.OK, MessageBoxIcon.Information);
					reader.Close();
					return;
				}
			}
			catch (Exception ex)
			{
				sb.Append("Could not retrieve sample!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this._form, sb.ToString(), "Get Sample Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}
			finally
			{
				if (reader != null)
				{
					if (!reader.IsClosed)
						reader.Close();
				}
				//if(conn != null)
				//    conn.Dispose();
				grid.EndUpdate();
			}
		}

		private void RetrieveSampleBatch(int num)
		{
			StringBuilder sb = new StringBuilder();
			string sql = "SELECT t.ID, t.DrawSample, " +
				" d.Protocol, d.Patient " +
				" FROM TestSamples t,DrawSamples d" +
				" WHERE t.BatchInNum =" + num +
				" AND d.ID=t.DrawSample " +
				" ORDER BY t.ID";

			BLCoreLabFormGridBaseImpl fgbl = (BLCoreLabFormGridBaseImpl)_gridBLs["TestSamples"];
			GridControl grid = fgbl.Grid;

			//SqlConnection conn = LoginForm.GetSqlConnection();
			IDataReader reader = null;
			try
			{
				reader = DataAccess.GetDataReader(sql);
				Sample samp = null;
				string message = "";

				if (reader.Read())
				{
					Cursor.Current = Cursors.WaitCursor;
					grid.BeginUpdate();
					do
					{
						samp = new Sample();
						samp.BatchInNum = num;
						samp.Tag = reader.GetInt32(0);
						if (IsInList((int)samp.Tag))
							continue;
						samp.DrawID = reader.GetInt32(1);
						samp.Protocol = reader.GetInt32(2);
						//get protocolInfo
						samp.ProtocolInfo = CoreLabUtils.GetProtocolInfo(samp.Protocol, out message);

						samp.PatientID = reader.GetInt32(3);
						//get the patient info
						samp.PatientInfo = CoreLabUtils.GetPatientInfo(samp.PatientID, out message);
						fgbl.AddRow(samp, 0);
						_alExistIDs.Add(samp.Tag);
					}
					while (reader.Read());
				}
				else
				{
					sb.Append("Batch was not found.");
					MessageBox.Show(this._form, sb.ToString(), "Draw Not Found",
						MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
				}
			}
			catch (Exception ex)
			{
				sb.Append("Could not retrieve batch!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this._form, sb.ToString(), "Retrieve Batch Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}
			finally
			{
				if (reader != null)
				{
					if (!reader.IsClosed)
						reader.Close();
				}
				//if(conn != null)
				//    conn.Dispose();
				grid.EndUpdate();
			}
		}

		private bool IsInList(int id)
		{
			GridControl grid = (GridControl)Forms.Utils.GetControlByName("TestSamples", this._form.Controls);
			GridStyleInfo gsi = null;

			if (grid.RowCount == 0)
				return false;
			for (int i = 1; i <= grid.RowCount; i++)
			{
				gsi = grid[i, 1];
				if (gsi.Text.Length > 0)
					if (Convert.ToInt32(gsi.CellValue) == id)
						return true;
			}
			return false;
		}
		#endregion select samples

		#region clear and display from grid
		private void ClearInfo()
		{
			this._testOutTo.SelectedIndex = -1;
			this._testOutTo.SelectedIndex = -1;
			this._testType.SelectedIndex = -1;
			this._testType.SelectedIndex = -1;
			this._unitOfMeasure.SelectedIndex = -1;
			this._unitOfMeasure.SelectedIndex = -1;
			this._result.Text = "";
			this._note.Text = "";
			this._outDate.Value = DateTime.Today;
			this._outDate.IsNullDate = true;
		}

		protected override void grd_CellDoubleClick(object sender, GridCellClickEventArgs e)
		{
			if (e.RowIndex < 1)
				return;
			if (this.FormMode == EditMode.Edit || this.FormMode == EditMode.New)
				FillControlsWithRowData(e.RowIndex);
		}

		private void FillControlsWithRowData(int row)
		{
			GridControl grid = ((BLCoreLabFormGridBaseImpl)this._gridBLs["TestSamples"]).Grid;
			//location			

			this._testOutTo.SelectedIndex = (int)grid[row, 6].CellValue;
			this._testType.SelectedIndex = (int)grid[row, 7].CellValue;
			this._unitOfMeasure.SelectedIndex = (int)grid[row, 8].CellValue;

			if (grid[row, 9].Text.Length == 0)
				this._outDate.IsNullDate = true;
			else
			{
				this._outDate.Value = (DateTime)grid[row, 9].CellValue;
				this._outDate.IsNullDate = false;
			}

			this._result.Text = grid[row, 10].Text;
			this._note.Text = grid[row, 11].Text;
		}
		#endregion get display data

		#region update remove data
		private void EditBatch()
		{
			this._btnEditBatch.Enabled = false;
			NewFromExistingEditDlg ebd = new NewFromExistingEditDlg(this);

			ebd.ButtonClick += new ctsu.Admin.Forms.CoreLab.NewFromExistingEditDlg.ButtonClickEventHandler(ebd_ButtonClick);
			ebd.Closing += new CancelEventHandler(ebd_Closing);
			ebd.Owner = this._form;
			ebd.Show();
		}

		private void ebd_ButtonClick(object sender, EditBatchEventArgs e)
		{
			if (e.ButtonName == "ReplaceSelected")
				EditReplaceSelected(e.ReplaceColumns, e.ColumnMatch);
			if (e.ButtonName == "ReplaceAll")
				EditReplaceAll(e.ReplaceColumns, e.ColumnMatch);
		}

		private void ebd_Closing(object sender, CancelEventArgs e)
		{
			NewFromExistingEditDlg ebd = (NewFromExistingEditDlg)sender;
			ebd.ButtonClick -= new NewFromExistingEditDlg.ButtonClickEventHandler(ebd_ButtonClick);
			ebd.Closing -= new CancelEventHandler(ebd_Closing);
			if (this._formMode == EditMode.Edit || this._formMode == EditMode.New)
				this._btnEditBatch.Enabled = true;
		}

		private void RemoveBatch()
		{
			GridControl grid = (GridControl)Forms.Utils.GetControlByName("TestSamples", this._form.Controls);

			GridRangeInfoList list;
			list = grid.Selections.GetSelectedRows(true, false);
			if (list.Count == 0)
				return;

			BLCoreLabFormGridBaseImpl fgbl = (BLCoreLabFormGridBaseImpl)this._gridBLs["TestSamples"];

			ArrayList alRows = new ArrayList();
			int row = 0;
			int top = 0;
			int bottom = 0;
			for (int i = 0; i < list.Count; i++)
			{
				top = list[i].Top;
				bottom = list[i].Bottom;
				if (bottom > top)
					GetSelectedRows(alRows, top, bottom);
				else
					alRows.Add(list[i].Top);
			}
			for (int i = 0; i < alRows.Count; i++)
			{
				row = (int)alRows[i];
				row -= i;
				DataRow dr = (DataRow)fgbl.Grid[row, 0].Tag;
				dr.RejectChanges();
				fgbl.RemoveRow(row);
			}
		}

		private void GetSelectedRows(ArrayList alRows, int top, int bottom)
		{
			int rows = bottom - top + 1;
			for (int i = 0; i < rows; i++)
				alRows.Add(top + i);
		}

		private void EditReplaceAll(bool[] replaceColumns, Hashtable columnMatch)
		{
			Sample samp = new Sample();
			samp.TestOutTo = -2;
			samp.TestType = -2;
			samp.UnitOfMeasure = -2;

			if (!SetReplacementColumns(replaceColumns, ref samp))
				return;

			BLCoreLabFormGridBaseImpl fgbl = (BLCoreLabFormGridBaseImpl)this._gridBLs["TestSamples"];

			for (int i = 1; i <= fgbl.Grid.RowCount; i++)
				fgbl.ReplaceRow(samp, i);

			this._form.btnSave.Enabled = true;
		}

		private void EditReplaceSelected(bool[] replaceColumns, Hashtable columnMatch)
		{
			GridControl grid = (GridControl)Forms.Utils.GetControlByName("TestSamples", this._form.Controls);

			GridRangeInfoList list;
			list = grid.Selections.GetSelectedRows(true, false);

			Sample samp = new Sample();
			if (!SetReplacementColumns(replaceColumns, ref samp))
				return;

			BLCoreLabFormGridBaseImpl fgbl = (BLCoreLabFormGridBaseImpl)this._gridBLs["TestSamples"];

			foreach (GridRangeInfo range in list)
			{
				for (int i = range.Top; i <= range.Bottom; i++)
				{
					fgbl.ReplaceRow(samp, i);
					this._form.btnSave.Enabled = true;
				}
			}
		}

		private bool SetReplacementColumns(bool[] replaceColumns, ref Sample samp)
		{
			StringBuilder sb = new StringBuilder();
			if (replaceColumns[0])
			{
				if (!VerifyAllColumns())
					return false;
				samp.TestOutTo = (int)this._testOutTo.SelectedValue;
				samp.TestType = (int)this._testType.SelectedValue;
				samp.UnitOfMeasure = (int)this._unitOfMeasure.SelectedValue;

				samp.OutDate = this._outDate.Value;
				if (this._result.Text.Length == 0)
					samp.Result = " ";
				else
					samp.Result = this._result.Text;
				if (this._note.Text.Length == 0)
					samp.Note = " ";
				else
					samp.Note = this._note.Text;
			}
			if (replaceColumns[1])
			{
				if (this._testOutTo.Text.Length == 0)
				{
					sb.Append("You must enter the tester!");
					MessageBox.Show(this._form, sb.ToString(), "Tester", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
					_testOutTo.Focus();
					return false;
				}
				samp.TestOutTo = (int)this._testOutTo.SelectedValue;
			}
			if (replaceColumns[2])
			{
				if (this._testType.Text.Length == 0)
				{
					sb.Append("You must enter the test type!");
					MessageBox.Show(this._form, sb.ToString(), "Test Type", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
					_testType.Focus();
					return false;
				}
				samp.TestType = (int)this._testType.SelectedValue;
			}
			if (replaceColumns[3])
			{
				if (this._unitOfMeasure.Text.Length == 0)
				{
					sb.Append("You must enter the unit of measure!");
					MessageBox.Show(this._form, sb.ToString(), "Unit Of Measure", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
					_unitOfMeasure.Focus();
					return false;
				}
				samp.UnitOfMeasure = (int)this._unitOfMeasure.SelectedValue;
			}
			if (replaceColumns[4])
			{
				if (this._outDate.IsNullDate)
				{
					sb.Append("You must enter the test date!");
					MessageBox.Show(this._form, sb.ToString(), "Test Date", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
					_outDate.Focus();
					return false;
				}
				samp.OutDate = this._outDate.Value;
			}
			if (replaceColumns[5])
			{
				if (_result.Text.Length == 0)
				{
					sb.Append("Are you sure you want to replace the result column with a blank entry!");
					if (MessageBox.Show(this._form, sb.ToString(), "Result", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.No)
					{
						_result.Focus();
						return false;
					}
					else
						samp.Result = " ";
				}
				else
					samp.Result = _result.Text;
			}
			if (replaceColumns[6])
			{
				if (_note.Text.Length == 0)
				{
					sb.Append("Are you sure you want to replace the comment column with a blank entry!");
					if (MessageBox.Show(this._form, sb.ToString(), "Comment", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.No)
					{
						_note.Focus();
						return false;
					}
					else
						samp.Note = " ";
				}
				else
					samp.Note = _note.Text;
			}
			return true;
		}

		private bool VerifyAllColumns()
		{
			StringBuilder sb = new StringBuilder();
			if (this._testOutTo.Text.Length == 0)
			{
				sb.Append("You must enter the tester!");
				MessageBox.Show(this._form, sb.ToString(), "Tester", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
				_testOutTo.Focus();
				return false;
			}
			if (this._testType.Text.Length == 0)
			{
				sb.Append("You must enter the test type!");
				MessageBox.Show(this._form, sb.ToString(), "Test Type", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
				_testType.Focus();
				return false;
			}
			if (this._unitOfMeasure.Text.Length == 0)
			{
				sb.Append("You must enter the unit of measure!");
				MessageBox.Show(this._form, sb.ToString(), "Unit Of Measure", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
				_unitOfMeasure.Focus();
				return false;
			}
			if (this._outDate.IsNullDate)
			{
				sb.Append("You must enter the test(out) date!");
				MessageBox.Show(this._form, sb.ToString(), "Out Date", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
				_outDate.Focus();
				return false;
			}

			if (_result.Text.Length == 0)
			{
				sb.Append("Are you sure you want to replace result with a blank entry!");
				if (MessageBox.Show(this._form, sb.ToString(), "Result", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.No)
				{
					_result.Focus();
					return false;
				}
			}

			if (_note.Text.Length == 0)
			{
				sb.Append("Are you sure you want to replace comment with a blank entry!");
				if (MessageBox.Show(this._form, sb.ToString(), "Comment", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.No)
				{
					_note.Focus();
					return false;
				}
			}
			return true;
		}
		#endregion update data

		#region new combo items
		private void NewTest()
		{
			StringBuilder sb = new StringBuilder();

			string sql = "SELECT Display " +
				" FROM TestType_L " +
				" WHERE 1=2";

			DataTable tableSchema;
			try
			{
				tableSchema = Forms.Utils.GetTableSchema(null, sql);
				NewListRecordDlg nd = new NewListRecordDlg("Display", "TestType_L", tableSchema);
				nd.ShowDialog(this._form);

				Forms.Utils.LoadCbo(_testType, "TestType_L", true);
				_testType.SelectedValue = nd.NewID;

				//reset the grid column comboBox
				BLCoreLabFormGridBaseImpl fgbl = (BLCoreLabFormGridBaseImpl)_gridBLs["TestSamples"];
				GridControl grid = fgbl.Grid;

				GridStyleInfo gsi = grid.ColStyles[3];
				SpecialLookup sl = (SpecialLookup)this._formInfo.SpecialLookups["TestType"];
				Forms.Utils.LoadCbo(sl, gsi);
			}
			catch (Exception ex)
			{
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				sb.Append("Error encountered while retrieving table schema for TestType.");
				sb.Append(Environment.NewLine);
				sb.Append("Error: " + ex.Message);
				MessageBox.Show(this._form, sb.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}
		}

		private void NewUnit()
		{
			StringBuilder sb = new StringBuilder();

			string sql = "SELECT Display " +
				" FROM UnitOfMeasure_L " +
				" WHERE 1=2";

			DataTable tableSchema;
			try
			{
				tableSchema = Forms.Utils.GetTableSchema(null, sql);
				NewListRecordDlg nd = new NewListRecordDlg("Display", "UnitOfMeasure_L", tableSchema);
				nd.ShowDialog(this._form);

				Forms.Utils.LoadCbo(_unitOfMeasure, "UnitOfMeasure_L", true);
				_unitOfMeasure.SelectedValue = nd.NewID;

				//reset the grid column comboBox
				BLCoreLabFormGridBaseImpl fgbl = (BLCoreLabFormGridBaseImpl)_gridBLs["TestSamples"];
				GridControl grid = fgbl.Grid;

				GridStyleInfo gsi = grid.ColStyles[4];
				SpecialLookup sl = (SpecialLookup)this._formInfo.SpecialLookups["UnitOfMeasure"];
				Forms.Utils.LoadCbo(sl, gsi);
			}
			catch (Exception ex)
			{
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				sb.Append("Error encountered while retrieving table schema for UnitOfMeasure.");
				sb.Append(Environment.NewLine);
				sb.Append("Error: " + ex.Message);
				MessageBox.Show(this._form, sb.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}
		}
		#endregion new

		#region print
		private void DoPrint()
		{
			if (!HasRows())
			{
				StringBuilder sb = new StringBuilder();
				sb.Append("There are no labels to print.");
				sb.Append(Environment.NewLine);
				MessageBox.Show(this._form, sb.ToString(), "No Labels", MessageBoxButtons.OK, MessageBoxIcon.Stop);
				return;
			}
			if (HasRowNoID())
			{
				StringBuilder sb = new StringBuilder();
				sb.Append("You must press save to give the new labels an ID.");
				sb.Append(Environment.NewLine);
				MessageBox.Show(this._form, sb.ToString(), "No Label ID", MessageBoxButtons.OK, MessageBoxIcon.Stop);
				return;
			}

			//DoSelectionTest();
			if (_chkPrintReport.Checked)
				PrintReport(0);

			if (_chkPerPatient.Checked)
				PrintReport(1);
		}

		private void PrintReport(int type)
		{
			StringBuilder sb = new StringBuilder();
			string formatFile = System.Windows.Forms.Application.StartupPath + "\\Bartender\\" + CremaConstants.LabelReportFormatFile;

			this._pDoc = new PrintDocument();
			this._pDoc.DefaultPageSettings.Landscape = true;
			this._pDlg = new PrintDialog();
			this._pDlg.Document = this._pDoc;

			if (this._pDlg.ShowDialog(this._form) == DialogResult.Cancel)
				return;

			bool doClear = false;
			GridControl grid = (GridControl)Forms.Utils.GetControlByName("TestSamples", this._form.Controls);

			Cursor.Current = Cursors.WaitCursor;
			if (type == 0)
				this._pDoc.PrintPage += new PrintPageEventHandler(_pDoc_PrintPage);
			else
				this._pDoc.PrintPage += new PrintPageEventHandler(_pDoc_PrintPerPatient);

			_sBatch = this._currentPrimaryID.ToString();
			try
			{
				System.Windows.Forms.Application.DoEvents();
				//				_btApp = new BarTender.ApplicationClass();							
				//				BarTender.Format btFmt = _btApp.Formats.Open(formatFile, true, "");

				_page = 1;
				_startRow = 1;
				_startRange = 0;

				if (this._chkPrintSelected.Checked)
				{
					if (grid.Selections.Count == 0)
					{
						sb.Append("Select rows to print or uncheck the 'Print Select Rows' check box.");
						MessageBox.Show(this._form, sb.ToString(), "No Rows Selected", MessageBoxButtons.OK, MessageBoxIcon.Stop);
						return;
					}
					else
					{
						//get the start row								
						GridRangeInfoList list = grid.Selections.GetSelectedRows(true, false);
						GridRangeInfo range = (GridRangeInfo)list[0];
						_startRow = range.Top;
					}
				}
				else
				{
					grid.Selections.Add(GridRangeInfo.Rows(1, grid.RowCount));
					doClear = true;
				}

				this._pDoc.Print();
			}
			catch (Exception ex)
			{
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				sb.Append("Could not start bartender server");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				MessageBox.Show(this._form, sb.ToString(), "Bartender Server Failed To Start", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			finally
			{
				//				if(_btApp != null)
				//				{
				//					_btApp.Quit(BarTender.BtSaveOptions.btDoNotSaveChanges);
				//					_btApp = null;
				//				}				
				if (type == 0)
					this._pDoc.PrintPage -= new PrintPageEventHandler(_pDoc_PrintPage);
				else
					this._pDoc.PrintPage -= new PrintPageEventHandler(_pDoc_PrintPerPatient);
				if (doClear)
					grid.Selections.Clear();
			}
		}

		private void DoSelectionTest()
		{
			bool doClear = false;
			GridControl grid = (GridControl)Forms.Utils.GetControlByName("TestSamples", this._form.Controls);
			GridRangeInfoList list;
			list = grid.Selections.GetSelectedRows(true, false);

			if (list.Count == 0)
			{
				grid.Selections.Add(GridRangeInfo.Rows(1, grid.RowCount));
				doClear = true;
			}

			list = grid.Selections.GetSelectedRows(true, false);

			for (int i = 0; i < list.Count; i++)
			{
				GridRangeInfo range = (GridRangeInfo)list[i];
				Console.WriteLine("");
				for (int j = range.Top; j <= range.Bottom; j++)
				{
					Console.WriteLine("Selected row: " + j.ToString());
				}
			}

			if (doClear)
				grid.Selections.Clear(false);

		}

		private void _pDoc_PrintPage(object sender, PrintPageEventArgs e)
		{

			StringBuilder sb = new StringBuilder();
			Graphics gfx = e.Graphics;
			float pageBottom = gfx.VisibleClipBounds.Height;
			float pageWidth = gfx.VisibleClipBounds.Width;
			float leftMargin = 50;
			float topMargin = 50;

			Font prntFont = new Font("Arial", 10);
			Font titleFont = new Font("Arial", 14, FontStyle.Bold);
			Font subTitleFont = new Font("Arial", 12);
			Font ColumnHeadFont = new Font("Arial", 10, FontStyle.Bold);

			Pen pen = new Pen(Color.Black);

			//get the line height with some padding
			float lineHeight = prntFont.GetHeight(e.Graphics) + 2;

			//set the drawing to the top left of the page
			float yPos = topMargin;
			float xPos = leftMargin;

			//print page #
			string page = "Page " + this._page;
			PrintingUtils.PrintCenter(page, e, prntFont, pageBottom - lineHeight);

			string batchDate = ((Syncfusion.Windows.Forms.Tools.DateTimePickerAdv)Forms.Utils.GetControlByName("BatchOutDate", this._form.Controls)).Value.ToShortDateString();
			GridControl grid = (GridControl)Forms.Utils.GetControlByName("TestSamples", this._form.Controls);

			//print title and subtitle
			if (this._page == 1)
			{
				PrintingUtils.PrintCenter("Core Lab - Test Samples Check-out & Results Report", e, titleFont, yPos);
				yPos += titleFont.GetHeight(e.Graphics) + 2;
				PrintingUtils.PrintCenter("New Samples From Existing", e, subTitleFont, yPos);
				yPos += titleFont.GetHeight(e.Graphics) + 2;

				sb.Append("Batch #: " + _sBatch);
				sb.Append("   Batch Date: " + batchDate);
				PrintingUtils.PrintCenter(sb.ToString(), e, subTitleFont, yPos);
				yPos += subTitleFont.GetHeight(e.Graphics) + 2;
			}
			else
			{
				sb.Append("Core Lab - Test Samples Checkout & Results - Batch #: " + _sBatch + " continued");
				PrintingUtils.PrintCenter(sb.ToString(), e, subTitleFont, yPos);
				yPos += subTitleFont.GetHeight(e.Graphics) + 2;
			}
			yPos += lineHeight;

			//print heading
			float c1 = 25;  //125
			float c2 = 150; //50
			float c3 = 200; //75			
			float c4 = 275; //125			
			float c5 = 400; //125			
			float c6 = 525; //75
			float c7 = 600; //100
			float c8 = 700; //100
			float c9 = 800; //125

			float c1W = 125; //id
			float c2W = 50; //origid
			float c3W = 75; //protocol
			float c4W = 125; //patient
			float c5W = 125; //test / units			
			float c6W = 75; //tester
			float c7W = 100; //out date			
			float c8W = 100; //result
			float c9W = 200; //note

			RectangleF rec = new RectangleF();

			gfx.DrawRectangle(Pens.Black, 23, yPos, (pageWidth - 48), lineHeight);
			gfx.FillRectangle(Brushes.LightBlue, 23, yPos, pageWidth - 48, lineHeight);

			PrintingUtils.SetRectangle(ref rec, c1, yPos, lineHeight, c1W);
			gfx.DrawString("ID", ColumnHeadFont, Brushes.Black, rec);
			PrintingUtils.SetRectangle(ref rec, c2, yPos, lineHeight, c2W);
			gfx.DrawString("Orig", ColumnHeadFont, Brushes.Black, rec);
			PrintingUtils.SetRectangle(ref rec, c3, yPos, lineHeight, c3W);
			gfx.DrawString("Protocol", ColumnHeadFont, Brushes.Black, rec);
			PrintingUtils.SetRectangle(ref rec, c4, yPos, lineHeight, c4W);
			gfx.DrawString("Patient", ColumnHeadFont, Brushes.Black, rec);
			PrintingUtils.SetRectangle(ref rec, c5, yPos, lineHeight, c5W);
			gfx.DrawString("Test/Units", ColumnHeadFont, Brushes.Black, rec);
			PrintingUtils.SetRectangle(ref rec, c6, yPos, lineHeight, c6W);
			gfx.DrawString("Out To", ColumnHeadFont, Brushes.Black, rec);
			PrintingUtils.SetRectangle(ref rec, c7, yPos, lineHeight, c7W);
			gfx.DrawString("Out Date", ColumnHeadFont, Brushes.Black, rec);
			PrintingUtils.SetRectangle(ref rec, c8, yPos, lineHeight, c8W);
			gfx.DrawString("Result", ColumnHeadFont, Brushes.Black, rec);
			PrintingUtils.SetRectangle(ref rec, c9, yPos, lineHeight, c9W);
			gfx.DrawString("Note", ColumnHeadFont, Brushes.Black, rec);
			yPos += lineHeight;

			lineHeight = prntFont.GetHeight(e.Graphics) + 18;
			//get the number of lines we can print
			int maxLines = (int)Math.Ceiling((double)((pageBottom - yPos) / lineHeight));
			maxLines -= 2;
			int curLine = 0;

			StringFormat fmt = new StringFormat();
			fmt.Trimming = StringTrimming.EllipsisCharacter;

			float yDraw;
			int iVal = 0;
			string sVal = "";
			PatientInfo pi = null;
			DateTime dtVal = new DateTime(0);

			GridRangeInfoList list = grid.Selections.GetSelectedRows(true, false);
			for (int i = _startRange; i < list.Count; i++)
			{
				GridRangeInfo range = (GridRangeInfo)list[i];
				for (int row = range.Top; row <= range.Bottom; row++)
				{
					if (row < _startRow)
						row = _startRow;

					if (curLine == maxLines)
					{
						_startRow = row;
						_startRange = i;
						this._page++;
						e.HasMorePages = true;
						return;
					}

					yDraw = yPos + 5;
					//test id
					iVal = (int)grid[row, 1].CellValue;
					//					_labelImage = CoreLabUtils.SetLabelFormatID(iVal.ToString("00000"), this._btApp);			
					//					gfx.DrawImage(this._labelImage,c1+5, yDraw, c1W, lineHeight);
					PrintingUtils.SetRectangle(ref rec, c1, yPos, lineHeight, c1W);
					gfx.DrawString(iVal.ToString("0000"), prntFont, Brushes.Black, rec, fmt);

					iVal = (int)grid[row, 2].CellValue;
					PrintingUtils.SetRectangle(ref rec, c2, yPos, lineHeight, c2W);
					gfx.DrawString(iVal.ToString("00000"), prntFont, Brushes.Black, rec);

					//protocol
					PrintingUtils.SetRectangle(ref rec, c3, yPos, lineHeight, c3W);
					sVal = grid[row, 4].Text;
					gfx.DrawString(sVal.ToString(), prntFont, Brushes.Black, rec);

					//patient					
					PrintingUtils.SetRectangle(ref rec, c4, yPos, lineHeight, c4W);
					pi = (PatientInfo)grid[row, 5].Tag;
					if (pi.Name.Length > 0)
						sVal = pi.Name + "/" + pi.GetMrnOrOtherIdentifier();
					else
						sVal = pi.GetMrnOrOtherIdentifier();
					gfx.DrawString(sVal, prntFont, Brushes.Black, rec, fmt);

					//test
					PrintingUtils.SetRectangle(ref rec, c5, yPos, lineHeight, c5W);
					sVal = grid[row, 7].FormattedText + "/" + grid[row, 8].FormattedText;
					gfx.DrawString(sVal, prntFont, Brushes.Black, rec, fmt);

					//out to
					sVal = grid[row, 6].FormattedText;
					PrintingUtils.SetRectangle(ref rec, c6, yPos, lineHeight, c6W);
					gfx.DrawString(sVal, prntFont, Brushes.Black, rec, fmt);

					sVal = ((DateTime)grid[row, 9].CellValue).ToShortDateString();
					PrintingUtils.SetRectangle(ref rec, c7, yPos, lineHeight, c7W);
					gfx.DrawString(sVal, prntFont, Brushes.Black, rec, fmt);

					PrintingUtils.SetRectangle(ref rec, c8, yPos, lineHeight, c8W);
					gfx.DrawString(grid[row, 10].Text, prntFont, Brushes.Black, rec, fmt);

					PrintingUtils.SetRectangle(ref rec, c9, yPos, lineHeight, c9W);
					gfx.DrawString(grid[row, 11].Text, prntFont, Brushes.Black, rec, fmt);


					gfx.DrawRectangle(Pens.Black, 23, yPos, (pageWidth - 48), lineHeight);
					yPos += lineHeight;
					curLine++;
				}
			}
		}

		private void _pDoc_PrintPerPatient(object sender, PrintPageEventArgs e)
		{
			StringBuilder sb = new StringBuilder();
			Graphics gfx = e.Graphics;
			float pageBottom = gfx.VisibleClipBounds.Height;
			float pageWidth = gfx.VisibleClipBounds.Width;
			float leftMargin = 50;
			float topMargin = 50;

			Font prntFont = new Font("Arial", 10);
			Font titleFont = new Font("Arial", 14, FontStyle.Bold);
			Font subTitleFont = new Font("Arial", 12);
			Font ColumnHeadFont = new Font("Arial", 10, FontStyle.Bold);

			Pen pen = new Pen(Color.Black);

			//get the line height with some padding
			float lineHeight = prntFont.GetHeight(e.Graphics) + 2;

			//set the drawing to the top left of the page
			float yPos = topMargin;
			float xPos = leftMargin;

			//print page #
			string page = "Page " + this._page;
			PrintingUtils.PrintCenter(page, e, prntFont, pageBottom - lineHeight);

			string batchDate = ((Syncfusion.Windows.Forms.Tools.DateTimePickerAdv)Forms.Utils.GetControlByName("BatchOutDate", this._form.Controls)).Value.ToShortDateString();
			GridControl grid = (GridControl)Forms.Utils.GetControlByName("TestSamples", this._form.Controls);

			//print title and subtitle
			if (this._page == 1)
			{
				PrintingUtils.PrintCenter("Core Lab - Test Samples Check-out & Results Report", e, titleFont, yPos);
				yPos += titleFont.GetHeight(e.Graphics) + 2;
				PrintingUtils.PrintCenter("New Samples From Existing", e, subTitleFont, yPos);
				yPos += titleFont.GetHeight(e.Graphics) + 2;

				sb.Append("Batch #: " + _sBatch);
				sb.Append("   Batch Date: " + batchDate);
				PrintingUtils.PrintCenter(sb.ToString(), e, subTitleFont, yPos);
				yPos += subTitleFont.GetHeight(e.Graphics) + 2;
			}
			else
			{
				sb.Append("Core Lab - Test Samples Checkout & Results - Batch #: " + _sBatch + " continued");
				PrintingUtils.PrintCenter(sb.ToString(), e, subTitleFont, yPos);
				yPos += subTitleFont.GetHeight(e.Graphics) + 2;
			}
			yPos += lineHeight;

			//print heading
			float c1 = 25;  //125
			float c2 = 150; //50
			float c3 = 200; //75			
			float c4 = 275; //125			
			float c5 = 400; //125			
			float c6 = 525; //75
			float c7 = 600; //100
			float c8 = 700; //100
			float c9 = 800; //125

			float c1W = 125; //id
			float c2W = 50; //origid
			float c3W = 75; //protocol
			float c4W = 125; //patient
			float c5W = 125; //test / units			
			float c6W = 75; //tester
			float c7W = 100; //out date			
			float c8W = 100; //result
			float c9W = 200; //note

			RectangleF rec = new RectangleF();

			gfx.DrawRectangle(Pens.Black, 23, yPos, (pageWidth - 48), lineHeight);
			gfx.FillRectangle(Brushes.LightBlue, 23, yPos, pageWidth - 48, lineHeight);

			PrintingUtils.SetRectangle(ref rec, c1, yPos, lineHeight, c1W);
			gfx.DrawString("ID", ColumnHeadFont, Brushes.Black, rec);
			PrintingUtils.SetRectangle(ref rec, c2, yPos, lineHeight, c2W);
			gfx.DrawString("Orig", ColumnHeadFont, Brushes.Black, rec);
			PrintingUtils.SetRectangle(ref rec, c3, yPos, lineHeight, c3W);
			gfx.DrawString("Protocol", ColumnHeadFont, Brushes.Black, rec);
			PrintingUtils.SetRectangle(ref rec, c4, yPos, lineHeight, c4W);
			gfx.DrawString("Patient", ColumnHeadFont, Brushes.Black, rec);
			PrintingUtils.SetRectangle(ref rec, c5, yPos, lineHeight, c5W);
			gfx.DrawString("Test/Units", ColumnHeadFont, Brushes.Black, rec);
			PrintingUtils.SetRectangle(ref rec, c6, yPos, lineHeight, c6W);
			gfx.DrawString("Out To", ColumnHeadFont, Brushes.Black, rec);
			PrintingUtils.SetRectangle(ref rec, c7, yPos, lineHeight, c7W);
			gfx.DrawString("Out Date", ColumnHeadFont, Brushes.Black, rec);
			PrintingUtils.SetRectangle(ref rec, c8, yPos, lineHeight, c8W);
			gfx.DrawString("Result", ColumnHeadFont, Brushes.Black, rec);
			PrintingUtils.SetRectangle(ref rec, c9, yPos, lineHeight, c9W);
			gfx.DrawString("Note", ColumnHeadFont, Brushes.Black, rec);
			yPos += lineHeight;

			lineHeight = prntFont.GetHeight(e.Graphics) + 18;
			//get the number of lines we can print
			int maxLines = (int)Math.Ceiling((double)((pageBottom - yPos) / lineHeight));
			maxLines -= 2;
			int curLine = 0;

			StringFormat fmt = new StringFormat();
			fmt.Trimming = StringTrimming.EllipsisCharacter;

			float yDraw;
			int iVal = 0;
			string sVal = "";
			PatientInfo pi = null;
			DateTime dtVal = new DateTime(0);

			GridRangeInfoList list = grid.Selections.GetSelectedRows(true, false);
			//assign current patient
			pi = (PatientInfo)grid[_startRow, 5].Tag;
			this._curPatient = pi.ID;
			for (int i = _startRange; i < list.Count; i++)
			{
				GridRangeInfo range = (GridRangeInfo)list[i];
				for (int row = range.Top; row <= range.Bottom; row++)
				{
					if (row < _startRow)
						row = _startRow;

					pi = (PatientInfo)grid[row, 5].Tag;
					if (curLine == maxLines || this._curPatient != pi.ID)
					{
						_startRow = row;
						_startRange = i;
						_curPatient = pi.ID;
						this._page++;
						e.HasMorePages = true;
						return;
					}

					yDraw = yPos + 5;
					//test id
					iVal = (int)grid[row, 1].CellValue;
					//					_labelImage = CoreLabUtils.SetLabelFormatID(iVal.ToString("0000"), this._btApp);			
					//					gfx.DrawImage(this._labelImage,c1+5, yDraw, c1W, lineHeight);
					PrintingUtils.SetRectangle(ref rec, c1, yPos, lineHeight, c1W);
					gfx.DrawString(iVal.ToString("0000"), prntFont, Brushes.Black, rec, fmt);

					iVal = (int)grid[row, 2].CellValue;
					PrintingUtils.SetRectangle(ref rec, c2, yPos, lineHeight, c2W);
					gfx.DrawString(iVal.ToString("00000"), prntFont, Brushes.Black, rec);

					//protocol
					PrintingUtils.SetRectangle(ref rec, c3, yPos, lineHeight, c3W);
					sVal = grid[row, 4].Text;
					gfx.DrawString(sVal.ToString(), prntFont, Brushes.Black, rec);

					//patient					
					PrintingUtils.SetRectangle(ref rec, c4, yPos, lineHeight, c4W);
					pi = (PatientInfo)grid[row, 5].Tag;
					if (pi.Name.Length > 0)
						sVal = pi.Name + "/" + pi.GetMrnOrOtherIdentifier();
					else
						sVal = pi.GetMrnOrOtherIdentifier();
					gfx.DrawString(sVal, prntFont, Brushes.Black, rec, fmt);

					//test
					PrintingUtils.SetRectangle(ref rec, c5, yPos, lineHeight, c5W);
					sVal = grid[row, 7].FormattedText + "/" + grid[row, 8].FormattedText;
					gfx.DrawString(sVal, prntFont, Brushes.Black, rec, fmt);

					//out to
					sVal = grid[row, 6].FormattedText;
					PrintingUtils.SetRectangle(ref rec, c6, yPos, lineHeight, c6W);
					gfx.DrawString(sVal, prntFont, Brushes.Black, rec, fmt);

					sVal = ((DateTime)grid[row, 9].CellValue).ToShortDateString();
					PrintingUtils.SetRectangle(ref rec, c7, yPos, lineHeight, c7W);
					gfx.DrawString(sVal, prntFont, Brushes.Black, rec, fmt);

					PrintingUtils.SetRectangle(ref rec, c8, yPos, lineHeight, c8W);
					gfx.DrawString(grid[row, 10].Text, prntFont, Brushes.Black, rec, fmt);

					PrintingUtils.SetRectangle(ref rec, c9, yPos, lineHeight, c9W);
					gfx.DrawString(grid[row, 11].Text, prntFont, Brushes.Black, rec, fmt);

					gfx.DrawRectangle(Pens.Black, 23, yPos, (pageWidth - 48), lineHeight);
					yPos += lineHeight;
					curLine++;
				}
			}
		}
		#endregion print
	}
}
